package com.ruoyi.syf.handler.escalation.strategy;

import com.ruoyi.syf.common.constant.EscalationDataType;
import com.ruoyi.syf.handler.escalation.EscalationStrategy;
import com.ruoyi.syf.mapper.RiskCheckRecordMapper;
import com.ruoyi.syf.service.EscalationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 隐患排查记录上报
 */
@Service
public class RecordEscalationStrategy implements EscalationStrategy {

    @Resource
    private EscalationService escalationService;

    @Resource
    private RiskCheckRecordMapper recordMapper;

    @Override
    public boolean escalation() {
        List<Map<String, Object>> data = recordMapper.escalation();
        //一次上报最多200条数据，需分片上报
        List<List<Map<String, Object>>> lists = splitList(data, 200);
//        List<List<Map<String, Object>>> lists = new ArrayList<>();
//        List<Map<String, Object>> listMap = new ArrayList<>();
//        Map<String, Object> map = new HashMap<>();
//        map.put("ID",1234567891);
//        map.put("data","测试测试测试测试");
//        listMap.add(map);
//        lists.add(listMap);

        if (lists.size() == 0){
            return true;
        }
        final boolean[] flag = {true};
        lists.forEach(list -> {
            boolean b = escalationService.socketEscalation(list, getEscalationType());
            if (!b) {
                flag[0] = false;
            }
        });
        return flag[0];
    }

    @Override
    public String getEscalationType() {
        return EscalationDataType.RECORD.getCode();
    }

    /**
     * 按指定长度拆分集合
     *
     * @param list 集合
     * @param len  拆分长度
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        //判断参数异常
        if (list == null || list.isEmpty() || len < 1) {
            return Collections.emptyList();
        }
        List<List<T>> result = new ArrayList<>();
        int size = list.size();
        //拆分的次数
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, (Math.min((i + 1) * len, size)));
            result.add(subList);
        }
        return result;
    }

}
